package ru.store;

import java.util.HashMap;
import java.util.Map;

import ru.store.paysystem.IPaySystem;

public class Store implements IStore {
	private Map<String, Map<String, Item>> items = new HashMap<String, Map<String, Item>>();
	private IPaySystem paySystem;
	
	public Store(IPaySystem paysystem)
	{
		paySystem = paysystem;
	}
	
	@Override
	public void addItem(Item item) throws Exception
	{
		if (items.get(item.getType()) == null)
			items.put(item.getType(), new HashMap<String, Item>());
		if ( items.get(item.getType()).get(item.getId()) == null )
			items.get(item.getType()).put(item.getId(), item);
		else
			throw new Exception(String.format("Store.Addbook: ID %s is not unique!", item.getId()));
	}

	@Override
	public void sellItem(String type, String id, int count) throws Exception
	{
		Item item = getItem(type, id);
		if(item == null)
			throw new ExceptionNoItem(String.format("Item %s %s not found in store", type, id));
		if(item.getCount() < count)
			throw new ExceptionNotEnoughItems(String.format("Not enought items %s %s in store", type, id));
		item.setCount(item.getCount() - count);
		paySystem.increaseProfit(count * item.getPrice());
		if(item.getCount() == 0)
			items.get(type).remove(id);
	}

	@Override
	public Item getItem(String type, String id)
	{
		Map<String, Item> tmp = items.get(type);
		if(tmp == null)
			return null;
		return tmp.get(id);
	}
	
	@Override
	public Map<String, Item> getItems(String type)
	{
		return items.get(type);
	}

	@Override
	public int getTotalAmount() {
		return items.size();
	}
}
